package com.power.project.dao.impl;

import com.power.project.dao.Ww_depart_userDaoCustom;
import com.power.project.model.Ww_depart_user;
import com.power.project.model.dto.UserDepartDTO;
import org.hibernate.query.internal.NativeQueryImpl;
import org.hibernate.transform.Transformers;
import org.springframework.stereotype.Repository;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import java.io.Serializable;
import java.util.List;

/**
 * 企业用户所在部门 持久层实现(hibernate)
 */

@Repository
public class Ww_depart_userDaoImpl implements Ww_depart_userDaoCustom<Ww_depart_user, Serializable> {

    @PersistenceContext
    private EntityManager entityManager;

    @Override
    public List<UserDepartDTO> getByUserIds(List<String> userIds, String tenantId) {
        StringBuilder dataSql = new StringBuilder("select wd.departid as \"departId\", wd.name, wdu.wwuserid as \"userId\", wdu.isleader as \"isLeader\"\n" +
                "from ww_depart_user wdu\n" +
                "         left join ww_depart wd on wd.departid = wdu.departid and wd.tenantid = :tenantid").append(Ww_userDaoImpl.BLANK_STRING);
        StringBuilder whereSql = new StringBuilder("where wdu.tenantid = :tenantid\n" +
                "  and wdu.wwuserid in (:userIds) and wd.departid is not null");
        dataSql.append(whereSql);
        Query dataQuery = entityManager.createNativeQuery(dataSql.toString());

        dataQuery.setParameter("userIds", userIds);
        dataQuery.setParameter("tenantid", tenantId);

        return dataQuery.unwrap(NativeQueryImpl.class).setResultTransformer(Transformers.aliasToBean(UserDepartDTO.class)).getResultList();
    }

    @Override
    public List<UserDepartDTO> getAllByTenantId(String tenantId) {
        StringBuilder dataSql = new StringBuilder("select wd.departid as \"departId\", wd.name, wdu.wwuserid as \"userId\", wu.name as \"userName\", wdu.isleader as \"isLeader\"\n" +
                "from ww_depart_user wdu\n" +
                "         left join ww_depart wd on wd.departid = wdu.departid and wd.tenantid = :tenantid " +
                "left join ww_user wu on wu.userid = wdu.wwuserid and wu.tenantid = :tenantid " +
                "left join ha_user hu on wu.userid = hu.userid and hu.deleted = 0").append(Ww_userDaoImpl.BLANK_STRING);
        StringBuilder whereSql = new StringBuilder("where wdu.tenantid = :tenantid and hu.userid is not null");
        dataSql.append(whereSql);
        Query dataQuery = entityManager.createNativeQuery(dataSql.toString());

        dataQuery.setParameter("tenantid", tenantId);

        return dataQuery.unwrap(NativeQueryImpl.class).setResultTransformer(Transformers.aliasToBean(UserDepartDTO.class)).getResultList();
    }
}